package com.ruoyi.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.RolePojo;
import com.ruoyi.common.core.domain.entity.SysMember;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginResponseVo;
import com.ruoyi.common.utils.JWTUtil;
import com.ruoyi.system.mapper.MemberMapper;
import com.ruoyi.system.mapper.RoleMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Api(tags = "登录模块")
@RestController
public class SysLoginController {


    @Autowired
    MemberMapper memberMapper;

    @Autowired
    RoleMapper roleMapper;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("登录获取token")
    @PostMapping("/login")
    public AjaxResult<LoginResponseVo> login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();

        QueryWrapper<SysMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", loginBody.getUsername()).eq("passwd", loginBody.getPassword());
        SysMember sysMember = memberMapper.selectOne(queryWrapper);

        if (sysMember == null) {
            return AjaxResult.error("该账户不存在/密码错误");
        }

        // 生成令牌
        String token = JWTUtil.createToken(sysMember.getId());
        LoginResponseVo loginResponseVo = new LoginResponseVo();
        loginResponseVo.setToken(token);

        QueryWrapper<RolePojo> rolePojoQueryWrapper = new QueryWrapper<>();
        rolePojoQueryWrapper.eq("id", sysMember.getRoleId());
        RolePojo roleInfo = roleMapper.selectOne(rolePojoQueryWrapper);
        loginResponseVo.setRoleInfo(roleInfo);
        return AjaxResult.success(loginResponseVo);
    }


}
